package safeCommitter.core.view.action;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.texteditor.ITextEditor;

import safeCommitter.utils.SCUtils;

public abstract class OpenEditorAction extends Action {
	protected String fClassName;
	private final boolean fActivate;

	/**
	 * Constructor for OpenEditorAction.
	 */
	protected OpenEditorAction(String testClassName) {
		this(testClassName, true);
	}

	public OpenEditorAction(String className, boolean activate) {
		fClassName = className;
		fActivate = activate;
	}

	/*
	 * @see IAction#run()
	 */
	@Override
	public void run() {
		ITextEditor textEditor = null;
		try {
			IJavaElement element = findElement(getLaunchedProject(), fClassName);
			if (element == null) {

				return;
			}
			textEditor = (ITextEditor) EditorUtility.openInEditor(element,
					fActivate);
		} catch (CoreException e) {

			return;
		}
		if (textEditor == null) {

			return;
		}
		reveal(textEditor);
	}

	protected Shell getShell() {
		return SCUtils.getShell();
	}

	protected IJavaProject getLaunchedProject() {
		return safeCommitter.core.template.Activator.getDefault()
				.getJavaProject();
	}

	protected String getClassName() {
		return fClassName;
	}

	protected abstract IJavaElement findElement(IJavaProject project,
			String className) throws CoreException;

	protected abstract void reveal(ITextEditor editor);

}
